import Json from '@/data/ResultJson'
import { AutoId } from '@/data/AutoId'
import { getRoleByIdAjax } from '@/data/RoleData'
const userList = [
  { id: 1, username: 'admin', password: 'admin', nickname: '管理员', status: 1, roleId: 1 },
  { id: 2, username: 'yanfa', password: 'yanfa', nickname: '研发', status: 1, roleId: 2 },
  { id: 3, username: 'yunwei', password: 'yunwei', nickname: '运维', status: 2, roleId: 2 }
]
function getIndexById (id) {
  id = parseInt(id)
  let index = -1
  for (let i = 0; i < userList.length; i++) {
    if (userList[i].id === id) {
      index = i
      break
    }
  }
  if (index === -1) {
    return Json.error('编号异常！')
  }
  return index
}

export function loginAjax (loginData = {}) {
  let loginInfo = null
  for (const user of userList) {
    if (user.username === loginData.username && user.password === loginData.password) {
      loginInfo = { ...user }
      break
    }
  }
  if (loginInfo) {
    if (loginInfo.status === 1) {
      return Json.success(loginInfo)
    }
    return Json.error('该用户已被封禁')
  }
  return Json.error('用户名或密码不正确')
}

export function getUserListAjax (searchInfo = {}) {
  let dataList = userList.filter(item => item.username === searchInfo.username || !searchInfo.username)
  dataList = dataList.filter(item => item.nickname === searchInfo.nickname || !searchInfo.nickname)
  dataList = dataList.filter(item => item.status === searchInfo.status || !searchInfo.status)
  dataList = dataList.filter(item => item.roleId === searchInfo.roleId || !searchInfo.roleId)
  dataList = dataList.reverse()

  for (const user of dataList) {
    const res = getRoleByIdAjax(user.roleId)
    user.role = { ...res.data }
  }
  console.log(dataList)
  return Json.success(dataList)
}

export function deleteUserAjax (id) {
  if (id === 1) {
    return Json.error('管理员禁止删除')
  }
  const index = getIndexById(id)
  userList.splice(index, 1)
  return Json.success()
}

export function getUserByIdAjax (id) {
  const index = getIndexById(id)
  return Json.success({ ...userList[index] })
}

export function saveOrUpdate (formData = {}) {
  if (formData.id) {
    const index = getIndexById(formData.id)
    userList[index] = { ...formData }
  } else {
    /* 重名验证 */
    for (const user of userList) {
      if (user.username === formData.username) {
        return Json.error('用户名已存在')
      }
    }

    formData.id = AutoId.userinfoId
    formData.password = '123456'
    userList.push(formData)
    AutoId.userinfoId++
  }
  return Json.success()
}

export function updatePassword (userinfo = {}) {
  const index = getIndexById(userinfo.id)
  userList[index].password = userinfo.password
  return Json.success()
}
